//
//  NetworkUnauthorizedPlugin.swift
//  LiveTrivia
//
//  Created by Gesen on 2017/11/22.
//  Copyright © 2017年 LiveTrivia. All rights reserved.
//
//  处理各种可能会返回 401 的情况

import Moya
//import Result

final class NetworkUnauthorizedPlugin: PluginType {
    
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        
        if
            let value = result.value,
            let code = try? value.map(Int.self, atKeyPath: "code"),
            code == 7 {
            unauthorized("你的登录已失效, 请重新登录")
        }
        
        if let response = result.value, response.statusCode == 401 {
            unauthorized("你的登录已失效, 请重新登录")
        }
        
        if let resultError = result.error {
            
            switch resultError {
                
            case .statusCode(let response) where response.statusCode == 401:
                unauthorized(resultError.localizedDescription)
                
            case .underlying(let err, _) where (err as NSError).code == 401:
                unauthorized(err.localizedDescription)
                
            default: break
            }
        }
    }
    
    /// 处理 401，注销登录状态并跳至登录
    ///
    /// - Parameter msg: 错误的描述
    func unauthorized(_ msg: String) {
//        AppUser.logout()
//        Toast.show(failure: msg)
    }
    
}
